﻿using System;
using System.Collections.ObjectModel;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.Threading;
using Hammock;
using Hammock.Web;

namespace _1906Ultras.Helpers
{
    public class HelperBase
    {
        protected RestRequest Request { get; private set; }
        private RestClient restClient { get; set; }

        public static bool IsErrorState { get; set; }

        protected string Authority
        {
            get { return restClient.Authority; }
            set { restClient.Authority = value; }
        }



        public HelperBase()
        {
            DispatcherHelper.Initialize();
            Request = new RestRequest();
            restClient = new RestClient(){Method = WebMethod.Get};
        }


        protected void AddParameter(string name, string value)
        {
            restClient.AddParameter(name, value);
        }

        protected void BeginRequest(Action<string> callback )
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() => GlobalLoading.Instance.IsLoading = true);
            restClient.BeginRequest(Request, (request, response, userState) =>
                                                 {
                                                     try
                                                     {
                                                         if (string.IsNullOrEmpty(response.Content)) throw new Exception("Response contains no content");
                                                         callback(response.Content);
                                                     }
                                                     catch (Exception e)
                                                     {
                                                         ErrorCallbackInternal(e);
                                                     }
  
                                                 });
        }




        protected void ErrorCallbackInternal(Exception e)
        {
            DispatcherHelper.CheckBeginInvokeOnUI(() =>
                                                      {
                                                          GlobalLoading.Instance.IsLoading = false;
                                                          if (!IsErrorState)
                                                          {
                                                              IsErrorState = true;
                                                              MessageBox.Show("Aw, bugger. Something went wrong.");
                                                          }
                                                      });
        }

    }
}
